import 'dart:convert';
import 'package:http/http.dart' as http;

import 'models.dart';
import 'parser.dart';
import 'sites.dart';

class ApiService {
  final VideoSite site;
  ApiService(this.site);

  Uri _buildListUri({int page = 1, String? keyword}) {
    final params = <String, String>{
      'ac': 'list',
      'pg': page.toString(),
    };
    if (keyword != null && keyword.trim().isNotEmpty) {
      params['wd'] = keyword.trim();
    }
    return Uri.parse(site.api).replace(queryParameters: params);
  }

  Uri _buildDetailUri(int id) {
    final params = <String, String>{
      'ac': 'detail',
      'ids': id.toString(),
    };
    return Uri.parse(site.api).replace(queryParameters: params);
  }

  Future<List<VodItem>> fetchList({int page = 1, String? keyword}) async {
    final uri = _buildListUri(page: page, keyword: keyword);
    print('[fetchList接口url] ${uri.toString()} page: $page keyword: $keyword');
    //设置超时时间为3秒
    final resp = await http.get(uri).timeout(const Duration(seconds: 5));
    print('[fetchList接口响应] ${site.name} ${resp.statusCode}');
    if (resp.statusCode != 200) {
      throw Exception('请求失败: ${resp.statusCode}');
    }
    final data = jsonDecode(resp.body);
    final list = (data['list'] ?? data['data'] ?? []) as List<dynamic>;
    return list.map((e) => VodItem.fromJson(e as Map<String, dynamic>)).toList();
  }

  Future<VodDetail> fetchDetail(int id) async {
    final uri = _buildDetailUri(id);
    print('[fetchDetail接口url] ${uri.toString()}');
    final resp = await http.get(uri).timeout(const Duration(seconds: 5));
    print('[fetchDetail接口响应] ${site.name} ${resp.statusCode}');
    if (resp.statusCode != 200) {
      throw Exception('请求失败: ${resp.statusCode}');
    }
    final data = jsonDecode(resp.body);
    final list = (data['list'] ?? data['data'] ?? []) as List<dynamic>;
    if (list.isEmpty) {
      throw Exception('未找到详情');
    }
    final raw = list.first as Map<String, dynamic>;
    final detail = VodDetail.fromJson(raw);
    final playFrom = raw['vod_play_from']?.toString();
    final playUrl = raw['vod_play_url']?.toString();
    final sources = parsePlaySources(playFrom, playUrl);
    // 附加站点名称到每个播放源
    final sourcesWithSite = sources.map((s) => PlaySource(s.name, s.episodes, site.name)).toList();
    return VodDetail(
      id: detail.id,
      name: detail.name,
      typeName: detail.typeName,
      pic: detail.pic,
      remarks: detail.remarks,
      actor: detail.actor,
      director: detail.director,
      area: detail.area,
      year: detail.year,
      content: detail.content,
      playSources: sourcesWithSite,
      siteName: site.name,
    );
  }
}